/*************************************************************************
	> File Name: server.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/13 22:54
 ************************************************************************/

#include "comm.hpp"

static void getMessage(int fd)
{
    char buffer[SIZE];
    while (1) {
        memset(buffer, '\0', sizeof buffer);
        ssize_t s = read(fd, buffer, sizeof buffer - 1);
        if (s > 0) {
            std::cout << "[" << getpid() << "]" << "client message>" << buffer << std::endl;
        } else if (s == 0) {
            std::cerr << "[" << "]" << "read the end of the file, client quit, server also quit." << std::endl;
            break;
        } else {
            perror("read");
            break;
        }
    }
}

int main(int argc, char *argv[])
{
    if (mkfifo(ipcPath.c_str(), MODE) < 0) {
        perror("mkfifo");
        exit(1);
    }
    Log("Make fifo file success", Debug) << " step 1" << std::endl;
    int fd = open(ipcPath.c_str(), O_RDONLY);
    if (fd < 0) {
        perror("open");
        exit(2);
    }
    Log("Open fifo file success", Debug) << " step 2" << std::endl;
    for (int i = 0; i < FORK_NUM; ++i) {
        pid_t id = fork();
        if (id == 0) {
            getMessage(fd);
            exit(1);
        }
    }
    for (int i = 0; i < FORK_NUM; ++i) {
        waitpid(-1, nullptr, 0);
    }
    close(fd);
    Log("Close fifo file success", Debug) << " step 3" << std::endl;
    unlink(ipcPath.c_str());
    Log("Delete fifo file success", Debug) << " step 4" << std::endl;
    return 0;
}


